package com.wang.jmonkey.common.handler.file;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.wang.jmonkey.common.property.FileSystemProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class FileSystemHandlerManager implements FileSystemHandlerAdapter {

    @Autowired
    private FileSystemProperty fileSystemProperty;

    @Autowired
    private ApplicationContext context;

    private List<FileSystemHandlerAdapter> list = new ArrayList<>();

    /**
     * 构建所有类型的file handler
     */
    @PostConstruct
    private void init() {
        Map<String, FileSystemHandlerAdapter> map = context.getBeansOfType(FileSystemHandlerAdapter.class);

        if (CollUtil.isNotEmpty(map)) {
            map.entrySet().forEach(entry -> {
                if (!(entry.getValue() instanceof FileSystemHandlerManager)) {
                    list.add(entry.getValue());
                }
            });
        }
    }

    /**
     * 上传文件到服务器
     * @param filePath 目标目录 如 /20201208/ct/test.dcm
     * @param file 上传的文件
     * @return boolean
     */
    @Override
    public boolean uploadFile(String filePath, InputStream file) {
        if (CollUtil.isNotEmpty(list)) {
           for (FileSystemHandlerAdapter handler : list) {
                if (handler.support(fileSystemProperty.getType())) {
                    return handler.uploadFile(filePath, file);
                }
            }
        }

        return false;
    }

    /**
     * 上传文件到服务器
     * @param filePath 目标目录 如 /20201208/ct/test.dcm
     * @param file 上传的文件
     * @return boolean
     */
    public boolean uploadFile(String filePath, File file) {
        try (InputStream is = new FileInputStream(file)) {
            return this.uploadFile(filePath, is);
        } catch (IOException e) {
            log.error("FileSystemHandlerManager uploadFile File error : ", e);
        }

        return false;
    }

    /**
     * 获取访问资源的前缀
     * @return 访问资源的前缀
     */
    @Override
    public String getResourcePrefix() {
        if (CollUtil.isNotEmpty(list)) {
            for (FileSystemHandlerAdapter handler : list) {
                if (handler.support(fileSystemProperty.getType())) {
                    return handler.getResourcePrefix();
                }
            }
        }

        return StrUtil.EMPTY;
    }

    @Override
    public boolean support(String type) {
        return false;
    }
}
